import 'package:common_utils/common_utils.dart';
import 'package:erp/data/model/login_response.dart';
import 'package:erp/main_state.dart';
import 'package:erp/routes/app_pages.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SplashController extends GetxController {
  @override
  void onReady() async {
    super.onReady();
    SharedPreferences sp = Get.find<SharedPreferences>();
    MainState ms = Get.find<MainState>();
    String tokenJsonStr = sp.getString("token") ?? "";
    String userInfoJsonStr = sp.getString("userInfo") ?? "";
    String menuCodeListStr = sp.getString("menuCodeList") ?? "";
    bool shouldLogin = true;
    if (!TextUtil.isEmpty(tokenJsonStr)) {
      Token? token = JsonUtil.getObj(tokenJsonStr, (v) => Token.fromJson(v as Map<String, dynamic>));
      UserInfo? userInfo = JsonUtil.getObj(userInfoJsonStr, (v) => UserInfo.fromJson(v as Map<String, dynamic>));
      List<String> menuCodeList = JsonUtil.getList(menuCodeListStr) ?? [];
      if (token != null &&
          token.expire != null &&
          DateTime.fromMillisecondsSinceEpoch(token.expire!).isAfter(DateTime.now())) {
        shouldLogin = false;
        ms.userInfo.value = userInfo;
        ms.token.value = token;
        ms.menuCodeList.addAll(menuCodeList);
      }
    }
    await Future.delayed(Duration(seconds: 3));
    shouldLogin ? Get.offNamed(Routes.LOGIN) : Get.offNamed(Routes.MAIN);
  }
}
